package com.yanqu.road.server.cmd.banquet.cross;

import com.yanqu.road.pb.banquet.BanquetProto;
import com.yanqu.road.pb.banquet.CrossBanquetProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.banquet.BanquetModule;
import com.yanqu.road.server.manger.banquet.CrossBanquetAutoOpenMgr;
import com.yanqu.road.server.manger.banquet.CrossBanquetMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;

@Cmd(code = Protocol.S_BANQUET_CROSS_PRE_OPEN_RESP, desc = "开启宴会返回")
public class CrossBanquetPreOpenRespCmd extends AbstractCommand {

	private int res;//返回的结果
	private String banquetId;
	private String invitationId;
	private int type;
	private String serverIdList;
	private String giftTypeAccept;
	private boolean autoOpen;
	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		CrossBanquetProto.PreOpenCrossBanquetResp reqMsg = CrossBanquetProto.PreOpenCrossBanquetResp.parseFrom(packet.getBytes());
		res = reqMsg.getRet();
		banquetId = reqMsg.getBanquetId();
		invitationId = reqMsg.getInvitationId();
		type = reqMsg.getType();
		serverIdList = reqMsg.getServerListStr();
		giftTypeAccept = reqMsg.getGiftTypeAccept();
		autoOpen = reqMsg.getAutoOpen();
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
		if(res != 0){
			ret = res;
			if(autoOpen){
				if(player == null){
					player = GamePlayerMgr.getPlayer(packet.getPlayerId());
				}
				CrossBanquetAutoOpenMgr.preUpdateAutoOpenFail(player, type);
			}
		}else{
			//假如遇到重启的时候,强行拉起用户再次同步开启宴会，或者用户掉线了,或者丢包了
			if(player == null){
				player = GamePlayerMgr.getPlayer(packet.getPlayerId());
			}
			ret = CrossBanquetMgr.openCrossBanquet(player,banquetId,invitationId,type,serverIdList,giftTypeAccept, autoOpen);
			if (0 == ret) {
				player.getModule(BanquetModule.class).updateUserBanquetSettingBanquetId(type, banquetId);
				if(autoOpen){
					//预开成功，先记录下宴会id
					CrossBanquetAutoOpenMgr.preUpdateAutoOpenSuccess(player, banquetId, type);
				}
			}else {
				if(autoOpen) {
					CrossBanquetAutoOpenMgr.preUpdateAutoOpenFail(player, type);
				}
			}
		}
	}

	@Override
	public void sendData(GamePlayer player) {
		if(ret != 0 && !autoOpen){
			BanquetProto.OpenBanquetResp.Builder respMsg = BanquetProto.OpenBanquetResp.newBuilder();
			respMsg.setRet(ret);
			player.sendPacket(Protocol.U_BANQUET_CROSS_OPEN, respMsg);
		}
	}

}
